package com.atung.merchant.service.impl;

import com.atung.merchant.config.auth.AuthUserMangerContext;
import com.atung.merchant.dto.OrderInfoEntity;
import com.atung.merchant.enums.MenuState;
import com.atung.merchant.enums.OrderState;
import com.atung.merchant.enums.RoomState;
import com.atung.merchant.enums.RoomType;
import com.atung.merchant.mapper.BusMerchantOrderMapper;
import com.atung.merchant.mapper.BusOrderMenuMapper;
import com.atung.merchant.po.BusMerchantOrder;
import com.atung.merchant.po.BusMerchantRoom;
import com.atung.merchant.po.BusOrderMenu;
import com.atung.merchant.result.ApiResult;
import com.atung.merchant.service.OrderService;
import com.atung.merchant.service.RoomService;
import com.atung.merchant.vo.IdRequest;
import com.atung.merchant.vo.MenuInfoResponse;
import com.atung.merchant.vo.OrderDetailsResponse;
import com.atung.merchant.vo.save.SaveOrderRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class OrderServiceImpl implements OrderService {

    //    @Resource
//    private BusMerchantRoomMapper busMerchantRoomMapper;
    @Resource
    private BusMerchantOrderMapper busMerchantOrderMapper;

    @Resource
    private BusOrderMenuMapper busOrderMenuMapper;

    @Resource
    private RoomService roomService;

    private static BusMerchantRoom createRoomName(RoomType roomType) {
        BusMerchantRoom busMerchantRoom = new BusMerchantRoom();
        busMerchantRoom.setId(System.currentTimeMillis());
        if (RoomType.PACK.equals(roomType)) {
            busMerchantRoom.setName("打包");
        } else {
            busMerchantRoom.setName("随机");
        }
        return busMerchantRoom;
    }

    @Override
    public OrderInfoEntity saveOrderService(SaveOrderRequest request) {
        BusMerchantRoom busMerchantRoom;
        //将当前房间选中为待使用
        if (request.getRoomType().equals(RoomType.ROOM)) {
            busMerchantRoom = roomService.selectRoomById(request.getRoomId());
            if (Objects.isNull(busMerchantRoom)) {
                throw new RuntimeException("房间信息不存在");
            }
            roomService.updateRoomStateById(request.getRoomId(), RoomState.useRoom);
        } else {
            busMerchantRoom = createRoomName(request.getRoomType());
        }

        if (Objects.nonNull(request.getId())) {
            //取消当前当前的使用状态
            BusMerchantOrder busMerchantOrder = busMerchantOrderMapper.selectById(request.getId());
            if (Objects.isNull(busMerchantOrder)) {
                throw new RuntimeException("数据不存在");
            }
            if (busMerchantOrder.getRoomType().equals(RoomType.ROOM.name())) {
                roomService.updateRoomStateById(busMerchantOrder.getRoomId(), RoomState.noUseRoom);
            }
        }

        Long orderId;
        //修改操作
        if (Objects.nonNull(request.getId())) {
            //查询当前房间编号
            BusMerchantOrder busMerchantOrder = busMerchantOrderMapper.selectById(request.getId());
            if (Objects.isNull(busMerchantOrder)) {
                return null;
            }
            busMerchantOrder.setRoomId(busMerchantRoom.getId());
            busMerchantOrder.setRoomName(busMerchantRoom.getName());
            busMerchantOrder.setRoomType(request.getRoomType().name());
            busMerchantOrderMapper.updateById(busMerchantOrder);
            orderId = busMerchantOrder.getId();
        } else {
            BusMerchantOrder busMerchantOrder = new BusMerchantOrder();
            busMerchantOrder.setRoomId(busMerchantRoom.getId());
            busMerchantOrder.setRoomName(busMerchantRoom.getName());
            busMerchantOrder.setRoomType(request.getRoomType().name());
            if (Objects.isNull(request.getId())) {
                busMerchantOrder.setId(request.getId());
            }
            busMerchantOrder.setMerchantId(AuthUserMangerContext.getMerchantId());

            int insert = busMerchantOrderMapper.insert(busMerchantOrder);
            orderId = busMerchantOrder.getId();
        }
        return OrderInfoEntity.builder().id(orderId)
                .roomName(busMerchantRoom.getName()).build();
    }

    @Override
    @Transactional
    public ApiResult cancelOrderService(IdRequest request) {

        BusMerchantOrder busMerchantOrder = busMerchantOrderMapper.selectById(request.getId());
        if (Objects.isNull(busMerchantOrder) || !busMerchantOrder.getMerchantId().equals(AuthUserMangerContext.getMerchantId())) {
            return ApiResult.ok();
        }
        QueryWrapper<BusOrderMenu>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",request.getId());
        queryWrapper.eq("menu_state",MenuState.COMPLETE.ordinal());
        Integer count = busOrderMenuMapper.selectCount(queryWrapper);
        if(count>0){
            return ApiResult.fail("有餐品已出餐,请到首页进行结算");
        }
        //解除房间占用情况
        if (busMerchantOrder.getRoomType().equals(RoomType.ROOM.name())) {
            roomService.updateRoomStateById(busMerchantOrder.getRoomId(), RoomState.noUseRoom);
        }
        //取消订单信息
        busMerchantOrder.setState(OrderState.CANCEL.ordinal());
        busMerchantOrderMapper.updateById(busMerchantOrder);
        //删除选择餐品
        QueryWrapper<BusOrderMenu>delectQueryWrapper=new QueryWrapper<>();
        delectQueryWrapper.eq("order_id",request.getId());
        busOrderMenuMapper.delete(delectQueryWrapper);
        return ApiResult.ok();
    }

    @Override
    @Transactional
    public ApiResult settlementOrderService(IdRequest request) {
        //
        BusMerchantOrder busMerchantOrder = busMerchantOrderMapper.selectById(request.getId());
        if (Objects.isNull(busMerchantOrder)) {
            return ApiResult.fail();
        }
        QueryWrapper<BusOrderMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", request.getId());
        queryWrapper.eq("menu_state", MenuState.COMPLETE.ordinal());
        List<BusOrderMenu> busOrderMenus = busOrderMenuMapper.selectList(queryWrapper);

        BigDecimal amount = busOrderMenus.stream().map(BusOrderMenu::getMenuPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        //修改房间信息
        if (busMerchantOrder.getRoomType().equals(RoomType.ROOM.name())) {
            roomService.updateRoomStateById(busMerchantOrder.getRoomId(), RoomState.noUseRoom);
        }
        busMerchantOrder.setAmount(amount);
        busMerchantOrder.setCollection(amount);
        busMerchantOrder.setState(OrderState.COMPLETE.ordinal());
        busMerchantOrderMapper.updateById(busMerchantOrder);
        //修改房间菜品信息
        busOrderMenuMapper.updateByOrderId(request.getId());
        return ApiResult.ok(amount);
    }

    @Override
    public OrderDetailsResponse queryOrderDetailsService(IdRequest request) {
        //获取订单信息

        BusMerchantOrder busMerchantOrder = busMerchantOrderMapper.selectById(request.getId());
        if (Objects.isNull(busMerchantOrder)) {
            return null;
        }
        //获取餐单列表
        QueryWrapper<BusOrderMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", request.getId());
        queryWrapper.orderByAsc("menu_state");
        queryWrapper.orderByDesc("creator_time");
        List<BusOrderMenu> busOrderMenus = busOrderMenuMapper.selectList(queryWrapper);
        BigDecimal pendingAmount = busOrderMenus.stream().filter(item -> item.getMenuState()
                        .equals(MenuState.COMPLETE.ordinal())).map(BusOrderMenu::getMenuPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal unservedAmount = busOrderMenus.stream().filter(item -> item.getMenuState()
                        .equals(MenuState.AWAIT.ordinal())).map(BusOrderMenu::getMenuPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        List<MenuInfoResponse> collect = busOrderMenus.stream().map(item -> {
            return MenuInfoResponse.builder()
                    .id(item.getId())
                    .name(item.getMenuName())
                    .menuPrice(item.getMenuPrice())
                    .menuState(MenuState.getMenuState(item.getMenuState()))
                    .build();
        }).collect(Collectors.toList());
        return OrderDetailsResponse.builder()
                .createTime(busMerchantOrder.getCreatorTime())
                .roomName(busMerchantOrder.getRoomName())
                .id(busMerchantOrder.getId())
                .pendingAmount(pendingAmount)
                .unservedAmount(unservedAmount)
                .menuInfoList(collect.size() == 0 ? null : collect)
                .build();
    }


}
